using admin.core.Entities.App;
using admin.core.Repositories;
using Microsoft.EntityFrameworkCore;

namespace admin.application.Services;

public class AppPermissionService : IAppPermissionService
{
    private readonly IRepository<AppPermission> _permissionRepo;

    public AppPermissionService(IRepository<AppPermission> permissionRepo)
    {
        _permissionRepo = permissionRepo;
    }

    public async Task<AppPermission> CreatePermissionAsync(AppPermission permission)
    {
        await _permissionRepo.AddAsync(permission);
        return permission;
    }

    public async Task<AppPermission?> UpdatePermissionAsync(Guid id, AppPermission permission)
    {
        var entity = await _permissionRepo.GetByIdAsync(id);
        if (entity == null) return null;
        entity.PermissionName = permission.PermissionName;
        entity.Code = permission.Code;
        // entity.Resources = permission.Resources; // 如需全量替换资源
        await _permissionRepo.UpdateAsync(entity);
        return entity;
    }

    public async Task DeletePermissionAsync(Guid id)
    {
        var entity = await _permissionRepo.GetByIdAsync(id);
        if (entity == null) throw new NotFoundException("权限不存在");
        entity.IsDeleted = true;
        await _permissionRepo.UpdateAsync(entity);
    }

    public async Task EnablePermissionAsync(Guid id)
    {
        var entity = await _permissionRepo.GetByIdAsync(id) ?? throw new Exception("权限不存在");
        entity.IsActived = true;
        await _permissionRepo.UpdateAsync(entity);
    }

    public async Task DisablePermissionAsync(Guid id)
    {
        var entity = await _permissionRepo.GetByIdAsync(id) ?? throw new Exception("权限不存在");
        entity.IsActived = false;
        await _permissionRepo.UpdateAsync(entity);
    }

    public async Task<AppPermission?> GetByCodeAsync(string code)
    {
        var all = await _permissionRepo.GetAllAsync();
        return all.FirstOrDefault(p => p.Code == code);
    }

    public async Task<List<AppPermission>> GetAllPermissionsAsync()
    {
        var all = await _permissionRepo.GetAllAsync();
        return all.Where(p => !p.IsDeleted)
                  .OrderBy(p => p.CreatedAt)
                  .ToList();
    }
}
